package com.emergency.direct.service.impl;

import com.emergency.direct.dao.*;
import com.emergency.direct.service.ScenarService;
import com.emergency.base.domain.*;
import com.emergency.common.util.CommonUtils;
import com.emergency.common.util.IdWorker;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class ScenarServiceImpl implements ScenarService {

    private final static Logger logger = LoggerFactory.getLogger(ScenarServiceImpl.class);

    @Autowired
    private ScenarDao scenarDao;

    @Autowired
    private ScenarArmyDao scenarArmyDao;

    @Autowired
    private ScenarEquipmentDao scenarEquipmentDao;

    @Autowired
    private ScenarRadiationDao scenarRadiationDao;

    @Autowired
    private ScenarTaskDao scenarTaskDao;

    @Autowired
    private ScenarWeatherDao scenarWeatherDao;

    @Autowired
    private IdWorker idWorker;

    @Override
    @Transactional
    public String add(Scenar scenar) {
        if(CommonUtils.isNullOrEmpty(scenar.getId())){
            scenar.setId(idWorker.nextId());
        }
        scenarDao.save(scenar);
       //保存装备，分队，辐射场，任务等基本信息
        armySave(scenar);
        equipmentSave(scenar);
        radiationSave(scenar);
        taskSave(scenar);
        weatherSave(scenar);

        return scenar.getId().toString();
    }

    private void weatherSave(Scenar scenar) {
        //先删除scenar相关的环境设置
        scenarWeatherDao.deleteByScenar(scenar.getId());

        ScenarWeather weather=scenar.getWeather();
        if(!CommonUtils.isNullOrEmpty(weather)) {
            weather.setId(idWorker.nextId());
            weather.setCreateTime(new Date());
            scenarWeatherDao.save(weather);
        }
    }


    private void taskSave(Scenar scenar) {
        //先删除scenar相关的任务
        scenarTaskDao.deleteByScenar(scenar.getId());

        List<ScenarTask> tasks=scenar.getTasks();
        if(!CommonUtils.isNullOrEmpty(tasks)){
            tasks.forEach(task->{
                task.setId(idWorker.nextId());
                task.setScenar(scenar);
            });
            scenarTaskDao.saveAll(tasks);
        }
    }

    private void radiationSave(Scenar scenar) {
        //先删除scenar相关的辐射场设置
        scenarRadiationDao.deleteByScenar(scenar.getId());

        ScenarRadiation radiation=scenar.getRadiation();
        if(!CommonUtils.isNullOrEmpty(radiation)) {
            radiation.setId(idWorker.nextId());
            radiation.setScenar(scenar);
            scenarRadiationDao.save(radiation);
        }
    }

    private void equipmentSave(Scenar scenar) {
        //先删除scenar相关的装备设置
        scenarEquipmentDao.deleteByScenar(scenar.getId());

        List<ScenarEquipment> equipments=scenar.getEquipments();
        if(!CommonUtils.isNullOrEmpty(equipments)){
            equipments.forEach(equipment->{
                equipment.setId(idWorker.nextId());
                equipment.setScenar(scenar);
            });
            scenarEquipmentDao.saveAll(equipments);
        }
    }

    private void armySave(Scenar scenar)
    {
        //先删除scenar相关的分队设置
        scenarArmyDao.deleteByScenar(scenar.getId());

        List<ScenarArmy> armys=scenar.getArmys();
        if(!CommonUtils.isNullOrEmpty(armys)){
            armys.forEach(army->{
                army.setId(idWorker.nextId());
                army.setScenar(scenar);
            });
            scenarArmyDao.saveAll(armys);
        }
    }


    @Override
    public Scenar get(Long id) {
        Scenar scenar=scenarDao.findById(id).orElse(null);
        if(CommonUtils.isNullOrEmpty(scenar)){
            logger.info("此想定信息为空！");
            return scenar;
        }
        scenar.setEquipments(scenarEquipmentDao.findAllByScenar(id));
        scenar.setArmys(scenarArmyDao.findAllByScenar(id));
        scenar.setRadiation(scenarRadiationDao.findByScenar(id));
        scenar.setTasks(scenarTaskDao.findAllByScenar(id));
        scenar.setWeather(scenarWeatherDao.findByScenar(id));
        return scenar;
    }

    @Override
    public Page<Scenar> findList(Map searchMap, int page, int size) {
        Specification<Scenar> specification = createSpecification(searchMap);
        PageRequest pageRequest =  PageRequest.of(page-1, size);
        return scenarDao.findAll(specification, pageRequest);
    }

    /**
     * 动态条件构建
     * @param searchMap
     * @return
     */
    private Specification<Scenar> createSpecification(Map searchMap) {

        return new Specification<Scenar>() {

            @Override
            public Predicate toPredicate(Root<Scenar> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                List<Predicate> predicateList = new ArrayList<Predicate>();

                // 想定名称
                if (searchMap.get("name") != null && !"".equals(searchMap.get("name"))) {
                    predicateList.add(cb.like(root.get("name").as(String.class), "%" + (String) searchMap.get("name") + "%"));
                }
                // 地点
                if (searchMap.get("place") != null && !"".equals(searchMap.get("place"))) {
                    predicateList.add(cb.like(root.get("place").as(String.class), "%" + (String) searchMap.get("place") + "%"));
                }

                return cb.and(predicateList.toArray(new Predicate[predicateList.size()]));

            }
        };

    }
}
